<template>

<div>
  <el-card>
    <el-form :inline="true" :model="queryInfo" ref="queryInfo" class="demo-form-inline">
      <el-form-item label="活动名" prop="activityName" >
        <el-input v-model="queryInfo.activityName" type="text" @clear="getActivityList" maxlength="20" minlength="2" show-word-limit clearable placeholder="活动名"></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="operator">
        <el-input v-model="queryInfo.operator" type="text" @clear="getActivityList" maxlength="5" minlength="1" show-word-limit clearable placeholder="发布人"></el-input>
      </el-form-item>
      <el-form-item label="活动时间" prop="date">
        <el-date-picker v-model="queryDate" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="getActivityList2">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addDialogVisible = true">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetQuery">重置查询/刷新</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="filterTable" :data="tableData" style="width: 100%" stripe  @selection-change="handleSelectionChange">
      <el-table-column type="index" label="#" width="50"></el-table-column>
      <el-table-column prop="activityName" label="活动 " width="200"></el-table-column>
      <el-table-column prop="signTime" label="报名时间" width="160"></el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="160"></el-table-column>
      <el-table-column prop="operator" label="发布人" width="100" :formatter="formatter"></el-table-column>
      <el-table-column prop="state" label="状态" width="100" :filters="[{ text: '未开始', value: 'WAIT' }, { text: '正在进行', value: 'DOING' },{ text: '已结束', value: 'END' }]" :filter-method="filterState" filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag :type="scope.row.state==='WAIT'? 'info' : (scope.row.state==='DOING'?'success':'danger')" disable-transitions>{{scope.row.state}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" width="100px">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enabled"  active-color="#13ce66" inactive-color="#ff4949" @change="enableChanged(scope.row)">

          </el-switch>
        </template>

      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button size="mini" type="primary" @click="handleView(scope.row.id)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55"></el-table-column>
    </el-table>
<!--底部分页-->
    <el-pagination @current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-size="queryInfo.pageSize" layout="total, prev, pager, next, jumper" :total="total">
    </el-pagination>

  </el-card>




<!--  弹出新增对话框-->
  <el-dialog title="新增活动" :visible.sync="addDialogVisible" width="50%" @close="closeDialog">

    <el-form :model="addForm" :rules="addRules" inline ref="addForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="addForm.activityName" clearable maxlength="20" minlength="2" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="operator">
        <el-input v-model="addForm.operator" clearable maxlength="5" minlength="1" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="活动积分" prop="integral">
        <el-input v-model.number="addForm.integral" clearable></el-input>
      </el-form-item>
      <el-form-item label="服务时长" prop="activityTime">
        <el-input v-model.number="addForm.activityTime" clearable></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="latitude">
        <el-input v-model="addForm.latitude" clearable></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="longitude">
        <el-input v-model="addForm.longitude" clearable></el-input>
      </el-form-item>


      <el-form-item label="活动简介" prop="introduction">
        <el-input type="textarea" v-model="addForm.introduction" clearable style="width: 525px"></el-input>
      </el-form-item>



      <el-form-item label="活动报名时间" prop="formTime1" >
        <el-date-picker v-model="formTime1" type="datetimerange" align="right" start-placeholder="开始报名日期" end-placeholder="截止报名日期" :default-time="['08:00:00', '20:00:00']">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="活动开始时间" prop="formTime2">
        <el-date-picker v-model="formTime2" type="datetimerange" align="right" start-placeholder="活动开始日期" end-placeholder="活动结束日期" :default-time="['08:00:00', '20:00:00']">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="上传图片" prop="addImageList">
        <el-upload action="http://localhost:8088/files/upload" :on-remove="handleRemove" :file-list="addImageList" ref="upload1" :on-success="filesUploadSuccess" :limit="3" list-type="picture-card" :on-preview="handlePictureCardPreview">
          <i class="el-icon-plus"></i>
        </el-upload>

        <el-dialog :visible.sync="imageDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

      </el-form-item>

    </el-form>



    <span slot="footer" class="dialog-footer">
    <el-button @click="cancelAddForm">取 消</el-button>
    <el-button type="primary"  @click="submitForm">确 定</el-button>
  </span>
  </el-dialog>

<!--  弹出编辑对话框-->
  <el-dialog title="修改活动" :visible.sync="editDialogVisible" width="50%" @close="closeEditDialog">

    <el-form :model="editForm" :rules="editRules" inline ref="editForm" label-width="100px" class="demo-ruleForm">

      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="editForm.activityName" clearable maxlength="20" minlength="2" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="operator">
        <el-input v-model="editForm.operator" clearable maxlength="5" minlength="1" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="活动积分" prop="integral">
        <el-input v-model.number="editForm.integral" clearable></el-input>
      </el-form-item>
      <el-form-item label="服务时长" prop="activityTime">
        <el-input v-model.number="editForm.activityTime" clearable></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="latitude">
        <el-input v-model="editForm.latitude" clearable></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="longitude">
        <el-input v-model="editForm.longitude" clearable></el-input>
      </el-form-item>


      <el-form-item label="活动简介" prop="introduction">
        <el-input type="textarea" v-model="editForm.introduction" clearable style="width: 525px"></el-input>
      </el-form-item>

      <el-form-item label="活动报名时间" prop="editTime1">
        <el-date-picker v-model="editTime1" type="datetimerange" align="right" :start-placeholder="start1" :end-placeholder="end1" :default-time="['08:00:00', '20:00:00']">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动开始时间" prop="editTime2">
        <el-date-picker v-model="editTime2" type="datetimerange" align="right" :start-placeholder="start2" :end-placeholder="end2" :default-time="['08:00:00', '20:00:00']">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="上传图片" prop="editImageList">
        <el-upload action="http://localhost:8088/files/upload" ref="upload2" :file-list="editImageList" :on-remove="handleEditRemove" :on-success="filesEditUploadSuccess" :limit="3" list-type="picture-card" :on-preview="handlePictureCardPreview">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="imageDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

      </el-form-item>

    </el-form>



    <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary"  @click="submitEditForm">确 定</el-button>
  </span>
  </el-dialog>
<!--  弹出查看对话框-->
  <el-dialog title="查看活动" :visible.sync="viewDialogVisible" width="50%">

    <el-form :model="viewForm" inline ref="viewForm" label-width="100px" >

      <el-form-item label="活动名称">
        <el-input v-model="viewForm.activityName" disabled></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="operator">
        <el-input v-model="viewForm.operator" disabled></el-input>
      </el-form-item>
      <el-form-item label="活动积分" prop="integral">
        <el-input v-model="viewForm.integral" disabled></el-input>
      </el-form-item>
      <el-form-item label="服务时长" prop="activityTime">
        <el-input v-model="viewForm.activityTime" disabled></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="latitude">
        <el-input v-model="viewForm.latitude" disabled></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="longitude">
        <el-input v-model="viewForm.longitude" disabled></el-input>
      </el-form-item>


      <el-form-item label="活动简介" prop="introduction">
        <el-input type="textarea" disabled v-model="viewForm.introduction" style="width: 525px"></el-input>
      </el-form-item>

      <el-form-item label="活动报名时间" prop="viewTime1">
        <el-date-picker type="datetimerange" disabled align="right" :start-placeholder="viewStart1" :end-placeholder="viewEnd1">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动开始时间" prop="editTime2">
        <el-date-picker type="datetimerange" disabled align="right" :start-placeholder="viewStart2" :end-placeholder="viewEnd2">
        </el-date-picker>
      </el-form-item>

    </el-form>

  </el-dialog>


</div>
</template>

<script>
// import Cookies from "js-cookie"
import axios from "axios";



export default {
  name: 'activity',
  data() {
    return {
      tableData: [],
      total: 0,
      queryDate: [],
      formTime1:[],
      formTime2:[],
      editTime1:[],
      editTime2:[],
      viewTime1:[],
      viewTime2:[],
      start1:'',
      end1:'',
      start2:'',
      end2:'',
      viewStart1:'',
      viewEnd1:'',
      viewStart2:'',
      viewEnd2:'',
      queryInfo: {
        activityName: '',
        operator:'',
        startDate: '',
        stopDate: '',
        pageNum: 1,
        pageSize: 8
      },
      text:'',
      addImageList:[],
      editImageList:[],
      removeImageList:[],//预移除的图片列表
      uploadedImages:0,//已上传的图片个数
      multipleSelection:[],
      addDialogVisible: false,
      editDialogVisible: false,
      imageDialogVisible: false,
      viewDialogVisible: false,
      addedForm:false,//是否提交了新增表单
      editedForm:false,//是否提交了编辑表单
      dialogImageUrl:'',
      viewForm: {
        activityName:'',
        operator: '',
        imageList:[],
        introduction:'',
        integral: '',
        activityTime:'',
        signTime: '',
        stopSignTime: '',
        startTime:'',
        endTime:'',
        longitude:'',
        latitude:''
      },
      editForm: {
        activityName:'',
        operator: '',
        imageList:[],
        introduction:'',
        integral: '',
        activityTime:'',
        signTime: '',
        stopSignTime: '',
        startTime:'',
        endTime:'',
        longitude:'',
        latitude:''
      },
      addForm: {
        activityName:'',
        operator: '',
        imageList:[],
        introduction:'',
        integral: '',
        activityTime:'',
        signTime: '',
        stopSignTime: '',
        startTime:'',
        endTime:'',
        longitude:'',
        latitude:''
      },
      addRules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        operator:[
          {required: true, message:'请填写发布人',trigger:'blur'},
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        integral:[
          {required: true, message:'请输入可获得活动积分',trigger: 'blur'},
          {type:'number', message: `请输入数字`, trigger: 'blur'}
        ],
        activityTime:[
          {required: true, message:'请输入可获得服务时长',trigger: 'blur'},
          { type:'number', message: '请输入数字', trigger: 'blur' }
        ],
        introduction:[
          {required: true, message:'请输入活动简介',trigger: 'blur'}
        ]
        // formTime1: [
        //   {required: true, message:'请输入报名时间', trigger: 'blur'}
        // ],
        // formTime2:[
        //   {required: true, message:'请输入活动时间',trigger: 'blur'}
        // ],
        // addImageList:[
        //   {required: true, message:'请选取图片',trigger: 'blur'}
        // ]

      },
      editRules:{
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        operator:[
          {required: true, message:'请填写发布人',trigger:'blur'},
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        integral:[
          {required: true, message:'请输入可获得活动积分',trigger: 'blur'},
          {type:'number', message: `请输入数字`, trigger: 'blur'}
        ],
        activityTime:[
          {required: true, message:'请输入可获得服务时长',trigger: 'blur'},
          { type:'number', message: '请输入数字', trigger: 'blur' }
        ],
        introduction:[
          {required: true, message:'请输入活动简介',trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.getActivityList()
  },
  methods: {

    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    formatter(row, column) {
      return row.operator;
    },
    filterState(value, row) {
      return row.state === value;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //查看操作
    handleView(id){
      axios({
        method: 'get',
        url: `http://localhost:8088/activity/${id}`
      }).then((res)=>{
        if(res.data.ok){
          this.viewForm = res.data.data
          console.log(this.viewForm.imageList)
          this.viewStart1 = res.data.data.signTime
          this.viewEnd1 = res.data.data.stopSignTime
          this.viewStart2 =res.data.data.startTime
          this.viewEnd2 = res.data.data.endTime
          // this.viewTime1.push(res.data.data.signTime)
          // this.viewTime1.push(res.data.data.stopSignTime)
          // this.viewTime2.push(res.data.data.startTime)
          // this.viewTime2.push(res.data.data.endTime)
          this.viewDialogVisible = true
          console.log('获取用户信息成功！')
        }else {
          this.$message.error("获取用户数据失败！")
        }
      })
    },
    //编辑操作
    handleEdit(id) {

      console.log(id)
      this.editedForm = false
      axios({
        method: 'get',
        url: `http://localhost:8088/activity/${id}`
      }).then((res)=>{
        if(res.data.ok){
          this.editForm = res.data.data
          console.log(this.editForm.imageList)
          this.start1 = res.data.data.signTime
          this.end1 = res.data.data.stopSignTime
          this.start2 =res.data.data.startTime
          this.end2 = res.data.data.endTime
          this.editTime1.push(res.data.data.signTime)
          this.editTime1.push(res.data.data.stopSignTime)
          this.editTime2.push(res.data.data.startTime)
          this.editTime2.push(res.data.data.endTime)
          this.editImageList = res.data.data.imageList
          this.editDialogVisible = true
          console.log('获取活动信息成功！')
        }else {
          this.$message.error("获取活动数据失败！")
        }
      })
    },
    //删除操作
    handleDelete(id) {
      console.log(id);
      this.$confirm('此操作将永久删除该活动, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios({
          method: 'delete',
          url:`http://localhost:8088/activity/${id}`
        }).then((res)=>{
          if(res.data.ok){
            this.$message.success("删除成功！")
            console.log('删除成功')
            this.getActivityList2()
          }else {
            this.$message.error("删除失败！")
            console.log('删除失败')
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getActivityList() {
      axios({
        method: 'post',
        url: 'http://localhost:8088/activity/getlist',
        data: this.queryInfo
      }).then((res)=>{
        if(res.data.ok){
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          console.log(this.tableData)
        }
      })
    },
    getActivityList2() {
      if(this.queryDate == null){
        this.queryInfo.activityName= ''
        this.queryInfo.operator = ''
        this.queryInfo.startDate = ''
        this.queryInfo.stopDate = ''
        this.getActivityList()
      }else {
        this.queryInfo.startDate = this.queryDate[0]
        this.queryInfo.stopDate = this.queryDate[1]
        this.getActivityList()
      }

    },
    //时间格式转换
    formatTime(time){
      let dateee = new Date(time ).toJSON();
      let date = new Date(+new Date(dateee)+ 8 * 3600 * 1000).toISOString().replace(/T/g,' ').replace(/\.[\d]{3}Z/,'');
      return date;
    },
    //取消提交表单
    cancelAddForm(){
      console.log('取消')
      this.addDialogVisible = false
    },
    //表单提交
    submitForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          // this.$refs.upload1.submit();
          this.addedForm = true
          this.addForm.signTime = this.formatTime(this.formTime1[0])
          this.addForm.stopSignTime = this.formatTime(this.formTime1[1])
          this.addForm.startTime = this.formatTime(this.formTime2[0])
          this.addForm.endTime = this.formatTime(this.formTime2[1])
          console.log(this.addForm.signTime)
          axios({
            method: 'post',
            url: 'http://localhost:8088/activity',
            data: this.addForm
          }).then((res)=>{
            if(res.data.ok){
              this.addDialogVisible = false
              this.$message.success("添加活动成功！")
            }else{
              this.$message.error('添加活动失败！')
            }
          });
        } else {
          alert('请填写完整！')
          return false;
        }
      });
    },
    //编辑的表单提交
    submitEditForm(){
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // this.addedForm = true
          //删除预移除的图片
          let num1 = this.removeImageList.length
          for(let i= 0;i<num1;i++){
            let image = this.removeImageList[i]
            axios({
              method: 'delete',
              url: image
            }).then((res)=>{
              if(!res.data.ok){
                this.$message.error("移除图片失败！")
              }else {

                console.log("移除成功！")
              }
            })
          }
          this.removeImageList = []
          this.editedForm = true
          this.editForm.signTime = this.formatTime(this.editTime1[0])
          this.editForm.stopSignTime = this.formatTime(this.editTime1[1])
          this.editForm.startTime = this.formatTime(this.editTime2[0])
          this.editForm.endTime = this.formatTime(this.editTime2[1])
          console.log(this.editForm)
          axios({
            method: 'put',
            url: 'http://localhost:8088/activity',
            data: this.editForm
          }).then((res)=>{
            if(res.data.ok){
              this.editDialogVisible = false
              this.$message.success("修改活动成功！")
            }else{
              this.$message.error('修改活动失败！')
            }
          });
          this.getActivityList2()
        } else {
          alert('请填写完整！')
          return false;
        }
      });
    },
    //关闭对话框之后重置对话框
    closeDialog() {

      console.log(this.addForm.imageList.length)
      let num = this.addForm.imageList.length
      //若上传图片后未点击确定便退出，则把已经上传的图片全部清除
      if(!this.addedForm){
        for(let i = 0;i<num;i++){
          console.log('pop')
          let end = this.addForm.imageList.pop()
          axios({
            method: 'delete',
            url: end.url
          }).then((res)=>{
            if(!res.data.ok){
              this.$message.error("移除图片失败！")
            }else {
              console.log("移除成功！")
            }
          })
        }
        this.addedForm = false
      }
      //清空表单，清空日期时间，清空图片列表
      this.$refs.upload1.clearFiles()
      this.$refs.addForm.resetFields()
      this.formTime1 = []
      this.formTime2 = []
      this.addForm.imageList = []
      this.getActivityList2()
      console.log("close addDialog")
    },
    //关闭编辑对话框之后重置对话框
    closeEditDialog() {
      //若变更图片后未点击确定便退出，则把已经上传的图片全部清除，并恢复原本图片
      let num1 = this.uploadedImages
      if(!this.editedForm){
        //先移除上传的图片
        for(let i = 0;i<num1;i++){
          console.log('移除已上传图片')
          let end = this.editForm.imageList.pop()
          axios({
            method: 'delete',
            url: end.url
          }).then((res)=>{
            if(!res.data.ok){
              this.$message.error("移除图片失败！")
            }else {
              console.log("移除成功！")
            }
          })
        }
        this.uploadedImages = 0
        this.editedForm = false

      }
      //清空表单，清空日期时间，清空图片列表
      this.$refs.editForm.resetFields()
      this.$refs.upload2.clearFiles()
      this.editTime1 = []
      this.editTime2 = []
      console.log("close editDialog")
    },
    //图片上传成功后的钩子函数
    filesUploadSuccess(res){
      console.log("上传成功！")
      let imageJson = {}
      imageJson.url = res.data
      this.addForm.imageList.push(imageJson)
      console.log(this.addForm.imageList)
    },
    //编辑中图片上传成功的钩子函数
    filesEditUploadSuccess(res){
      console.log("编辑图片上传成功！")
      let imageJson = {}
      imageJson.url = res.data
      console.log(res.data)
      this.editForm.imageList.push(imageJson)
      this.uploadedImages++
      console.log(this.editForm.imageList)
    },
    //图片移除
    handleRemove(file) {
      // let end = this.addForm.imageList.pop()
      // console.log(file,fileList)
      // console.log(end)
      console.log('移除图片')
      let end = file.response.data
      console.log('移除：'+end)
      axios({
        method: 'delete',
        url: end
      }).then((res)=>{
        if(!res.data.ok){
          this.$message.error("移除图片失败！")
        }else {
          console.log("移除成功！")
        }
      })
    },
    //编辑中的图片移除
    handleEditRemove(file) {
      // console.log(file.url)
      //若取消编辑则重新恢复预移除的图片
      console.log('移除图片')
      console.log(file)
      let num =this.editForm.imageList.length
      console.log('预移除：'+file.url)
      this.removeImageList.push(file.url)
      for(let i = 0;i< num ;i++){
        if(this.editForm.imageList[i].url === file.url){
          console.log('移除的是：'+this.editForm.imageList[i].url)
          this.editForm.imageList.splice(i,1)
          console.log(this.editForm.imageList)
          break
        }
      }

    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.imageDialogVisible = true;
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getActivityList()
    },
    //改变启用状态
    enableChanged(activity) {
      axios({
        method: 'put',
        url: `http://localhost:8088/activity/${activity.id}/${activity.enabled}`
      }).then((res)=>{
        if(!res.data.ok){
          this.$message.error("修改启用状态失败！")
        }else{
          this.$message.success("修改启用状态成功！")
          console.log("修改启用状态成功！")
        }
      })
      console.log(activity)
    },
    resetQuery(){
      this.queryInfo.activityName= ''
      this.queryInfo.operator = ''
      this.queryInfo.startDate = ''
      this.queryInfo.stopDate = ''
      this.getActivityList()
    }


  },
}
</script>

<style scoped>


</style>
